//
//  MobileAddressBookViewController.m
//  OA
//
//  Created by yy on 17/7/3.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "MobileAddressBookViewController.h"
#import <AddressBook/AddressBook.h>
#import "MobileManModel.h"
@interface MobileAddressBookViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *arrOfMobile;

@end

@implementation MobileAddressBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"手机联系人";
    [self initOfDataSouce];
    [self initializeUserInterface];
}
- (void)initOfDataSouce{
    _arrOfMobile = [NSMutableArray array];
    [self loadPresion];
    
}

//查看是否已经获取通讯录权限
- (void)loadPresion{
    ABAddressBookRef addressBookref = ABAddressBookCreateWithOptions(NULL, NULL);
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookref, ^(bool granted, CFErrorRef error) {
            CFErrorRef *error1 = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
            [self copyAddressBook:addressBook];
        });
    }else if(ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        CFErrorRef *error1 = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
        [self copyAddressBook:addressBook];
        
    }else{
        UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有获取通讯录权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        alert.delegate = self;
        [alert show];
    }
}

- (void)copyAddressBook:(ABAddressBookRef)addressBook{
    //获取联系人个数
    CFIndex numberOfPeoples = ABAddressBookGetPersonCount(addressBook);
    CFArrayRef peoples = ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSLog(@"有%ld个联系人", numberOfPeoples);
    //循环获取联系人
    for (int i = 0; i < numberOfPeoples; i++) {
        ABRecordRef person = CFArrayGetValueAtIndex(peoples, i);
        MobileManModel *mobileMan = [[MobileManModel alloc] init];
        mobileMan.firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        mobileMan.lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        mobileMan.nickName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
        mobileMan.organiztion = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        mobileMan.headImage = (__bridge NSData*)ABPersonCopyImageData(person);
        
        
        if (mobileMan.firstName && mobileMan.lastName) {
            mobileMan.name = [NSString stringWithFormat:@"%@%@",mobileMan.lastName, mobileMan.firstName];
        }else if(!mobileMan.firstName){
            mobileMan.name = mobileMan.lastName;
        }else{
            mobileMan.name = mobileMan.firstName;
        }
        if (!mobileMan.name) {
            mobileMan.name = mobileMan.organiztion;
        }
        if (mobileMan.nickName) {
            mobileMan.name =[NSString stringWithFormat:@"%@", mobileMan.nickName];
        }
        
        //读取电话多值
        NSMutableArray *phoneArray = [[NSMutableArray alloc] init];
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * tempstr = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            NSArray *array = [NSArray arrayWithObjects:personPhoneLabel, tempstr, nil];
            [phoneArray addObject:array];
        }
        mobileMan.phones = phoneArray;
        [self.arrOfMobile addObject:mobileMan];
    }

    [self performSelectorOnMainThread:@selector(reloadTable) withObject:nil waitUntilDone:YES];
}

- (void)reloadTable{
    [self.tableView reloadData];
    
}
- (void)initializeUserInterface{
    _tableView.tableFooterView = [UIView new];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark —————— 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return   _arrOfMobile.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
    }
     MobileManModel *mobileMan = _arrOfMobile[indexPath.row];
    
    cell.textLabel.text = mobileMan.name;
//    NSArray *array = [mobileMan.phones objectAtIndex:0];
//    NSString *phoneStr = [array objectAtIndex:1];
//    cell.detailTextLabel.text = phoneStr;
    cell.imageView.image = [UIImage imageWithData:mobileMan.headImage];
     NSLog(@"mobileManphone%@",mobileMan.phones);
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
      NSLog(@"点击");
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MobileManModel *mobileMan = _arrOfMobile[indexPath.row];
    NSArray *array = [mobileMan.phones objectAtIndex:0];
    NSString *phoneStr = [array objectAtIndex:1];
    [self AlertController:phoneStr];

}

- (void)AlertController:(NSString *)phone{
    //初始化
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"电话" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    //BTN
    UIAlertAction *refuseAction = [UIAlertAction actionWithTitle:@"发短信" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sendSmsAction:phone];
    }];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"打电话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self phoneAction:phone];
    }];
    UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    
    
    
    [alert addAction:refuseAction];
    [alert addAction:okAction];
    [alert addAction:noAction];
    alert.popoverPresentationController.permittedArrowDirections  =UIPopoverArrowDirectionDown;
    //页面设置
   
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)sendSmsAction:(NSString *)phone{
    
    if (phone.length == 0) {
        [MBProgressHUD showError:@"电话为空！"];
    }
    
    NSString *phoneNumber = phone;
    NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"sms://%@", phoneNumber]];
    //         NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", @"10086"]];
    
    UIWebView *mCallWebview = [[UIWebView alloc] init] ;
    [self.view addSubview:mCallWebview];
    [mCallWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    

}

- (void)phoneAction:(NSString *)phone{
    if (phone.length == 0) {
        [MBProgressHUD showError:@"电话为空！"];
        return;
    }

    NSString *phoneNumber = phone;
    NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNumber]];
    //     NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", @"10086"]];
    
    UIWebView *mCallWebview = [[UIWebView alloc] init] ;
    [self.view addSubview:mCallWebview];
    [mCallWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    

}

@end
